package chapter1;

import java.util.Iterator;

/**
 * This Class is not thread safe.
 *
 * @param <T>
 */
public class ArrayStack<T> implements Stack<T> {
    private int index = 0;

    private T[] arr = null;

    private final static int DEFAULT_SIZE = 16;

    public ArrayStack() {
        arr = (T[]) new Object[DEFAULT_SIZE];
    }

    public ArrayStack(int size) {
        arr = (T[]) new Object[size];
    }


    @Override
    public void push(T item) {
        if (item == null) {
            throw new NullPointerException("item can not be null");
        }
        if (index >= arr.length) {
            resize(arr.length * 2);
        }
        arr[index++] = item;
    }

    private void resize(int size) {
        T[] temp = (T[]) new Object[size];
        for (int i = 0; i < index; i++) {
            temp[i] = arr[i];
        }
        arr = temp;
    }

    @Override
    public T pop() throws ArrayIndexOutOfBoundsException {
        if (index == 0) {
            throw new ArrayIndexOutOfBoundsException();
        }
        T item = arr[--index];
        //clear the reference of the object, let the GC to free the memory
        arr[index] = null;
        //if the current capacity is 1/4 of array max capacity, resize the array max capacity to 1/2
        if (index > 0 && index * 4 == arr.length) {
            resize(arr.length / 2);
        }
        return item;
    }

    @Override
    public boolean isEmpty() {
        return index == 0;
    }

    @Override
    public int size() {
        return arr.length;
    }

    @Override
    public Iterator<T> iterator() {
        return new ReverseArrayIterator();
    }

    private class ReverseArrayIterator implements Iterator<T> {
        private int currentIndex = index;

        @Override
        public boolean hasNext() {
            return currentIndex > 0;
        }

        @Override
        public T next() {
            return arr[--currentIndex];
        }
    }
}
